import { View, Text } from '@tarojs/components';
import { AtIcon } from 'taro-ui';
import clsx from 'clsx';
import { useEffect, useState } from 'react';
import './index.scss';

const QTabBar = (props: any) => {
  const {
    className,
    list = [],
    lineCount = 4,
    onClick,
    value = 0,
  } = props;

  const [currentIndex, setCurrentIndex] = useState(value);

  useEffect(() => {
    setCurrentIndex(value);
  }, [value]);

  const clickTab = (item: any, index: number) => {
    if (onClick) {
      onClick(item, index);
    }
    setCurrentIndex(index);
  };

  const renderTabs = () => list?.map((item, index) => (
    <View
      className={clsx('q-single-tab-bar flex-center',
        currentIndex === index ? 'q-active-bar' : '',
        index === (currentIndex - 1) ? 'q-active-right-border' : '',
        ((index + 1) % lineCount === 0 || index === list.length - 1) ? 'q-last-bar' : '',
        (index % lineCount === 0) ? 'q-first-bar' : '')}
      onClick={() => {
        clickTab(item, index);
      }}
    >
      {item.icon ? <AtIcon className="mr-20" value={`iconfont ${item.icon}`} size={16} /> : null}
      <Text className="fs-24 lh-40">{item.title}</Text>
    </View>
  ));
  return (
    <View className={clsx(className, 'q-tab-bar-container')} style={{ gridTemplateColumns: `repeat(${lineCount}, 1fr)` }}>
      {renderTabs()}
    </View>
  );
};

export default QTabBar;
